package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

//@WebFilter("/*")
public class LoginFilter implements Filter {
    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER = "token";
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String path = req.getServletPath();
        boolean isLoginReq = ObjectUtil.equal(LOGIN_PATH, path);
        if(isLoginReq){
            chain.doFilter(request, response);
            return;
        }
        String token = req.getHeader(TOKEN_HEADER);
        if(ObjectUtil.isNull(token)){
            res.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            chain.doFilter(request, response);
            return;
        }
        catch (Exception e) {
            res.setStatus(401);
            return;
        }
    }
}

